Page({
  data: {
    list: [],  
    content: '',  
    webSocket: null,
    avatarUrl: "" 
  },

  onLoad(options) {
    const that = this;

    if (options.avatarUrl) {
      that.setData({ avatarUrl: decodeURIComponent(options.avatarUrl) });
    }

    that.data.webSocket = wx.connectSocket({
      url: 'ws://172.18.23.53:8080/shopping/ws/consumer/waiter',  
      header: {
        'content-type': 'application/json'
      }
    });

    // 监听 WebSocket 消息
    that.data.webSocket.onMessage(function (res) {
      const item = {
        id: 'waiter',
        content: res.data
      };
      const list = that.data.list.concat(item);
      that.setData({ list });
    });

    // 监听 WebSocket 关闭
    that.data.webSocket.onClose(() => {
      console.log('WebSocket 已关闭');
      that.setData({ webSocket: null });
    });

    // 监听 WebSocket 错误
    that.data.webSocket.onError(err => {
      console.error('WebSocket 错误:', err);
    });
  },

  onUnload() {
    if (this.data.webSocket) {
      this.data.webSocket.close();
    }
  },

  contentBindKeyInput(e) {
    this.setData({
      content: e.detail.value.trim()
    });
  },

  send() {
    const that = this;
    const content = that.data.content;
    if (!content) return;

    wx.showLoading({ title: '提交中' });

    that.data.webSocket.send({
      data: content,
      success: function () {
        wx.hideLoading();
        const item = { id: 'consumer', content };
        const list = that.data.list.concat(item);
        that.setData({ list, content: '' });
      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({ title: '发送失败', icon: 'none' });
        console.error('发送失败:', err);
      }
    });
  }
});
